<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="合作商家名称" prop="merchantName">
        <el-input
          v-model="queryParams.merchantName"
          placeholder="合作商家名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商家电话" prop="merchantPhone">
        <el-input
          v-model="queryParams.merchantPhone"
          placeholder="请输入商家电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态 " clearable>
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" type="index" width="80" />
      <el-table-column label="合作商家名称" align="center" prop="merchantName" />
      <el-table-column label="商家地址" align="center" prop="merchantAddress" />
      <el-table-column label="商家电话" align="center" prop="merchantPhone" />
      <el-table-column label="订单状态 " align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="orderNumber" />
      <el-table-column label="送货员" align="center" prop="empId">
        <template #default="scope">
          {{ getEmployeeName(scope.row.empId) }}
        </template>
      </el-table-column>
      <el-table-column label="所属区域" align="center" prop="regionId">
        <template #default="scope">
          {{ getRegionName(scope.row.regionId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
           <el-button link type="primary" @click="handleDispatch(scope.row)" v-hasPermi="['manage:order:edit']" :disabled="scope.row.status !== 1">派单</el-button>
          <el-button link type="primary" @click="handleViewDetail(scope.row)" v-hasPermi="['manage:order:edit']">订单详细</el-button>
         
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['manage:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看订单详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions border :column="2">
        <el-descriptions-item label="订单ID">{{ detailForm.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ detailForm.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="合作商家">{{ detailForm.merchantName }}</el-descriptions-item>
        <el-descriptions-item label="商家电话">{{ detailForm.merchantPhone }}</el-descriptions-item>
        <el-descriptions-item label="商家地址">{{ detailForm.merchantAddress }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="order_status" :value="detailForm.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="所属区域">{{ getRegionName(detailForm.regionId) }}</el-descriptions-item>
        <el-descriptions-item label="送货员">{{ getEmployeeName(detailForm.empId) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailForm.updateTime }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="center">商品明细</el-divider>
      <el-table :data="detailForm.tbOrderDetailList" style="width: 100%">
        <el-table-column label="商品ID" prop="productId" align="center" />
        <el-table-column label="商品名称" prop="productName" align="center" />
        <el-table-column label="数量" prop="number" align="center" />
        <el-table-column label="单价" prop="unitPrice" align="center" />
        <el-table-column label="总价" prop="totalPrice" align="center" />
      </el-table>
      
      <el-descriptions border :column="1" style="margin-top: 20px;">
        <el-descriptions-item label="订单总金额">¥{{ calculateTotalAmount(detailForm.tbOrderDetailList) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 派单对话框 -->
    <el-dialog :title="dispatchTitle" v-model="dispatchOpen" width="500px" append-to-body>
      <el-form ref="dispatchRef" :model="dispatchForm" :rules="dispatchRules" label-width="100px">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="dispatchForm.orderNumber" disabled />
        </el-form-item>
        <el-form-item label="送货员" prop="empId">
          <el-select v-model="dispatchForm.empId" placeholder="请选择送货员" style="width: 100%">
            <el-option
              v-for="employee in matchingEmployees"
              :key="employee.employeeId"
              :label="employee.name"
              :value="employee.employeeId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDispatch">确 定</el-button>
          <el-button @click="cancelDispatch">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改货单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-divider content-position="center">派单</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTbOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTbOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="tbOrderDetailList" :row-class-name="rowTbOrderDetailIndex" @selection-change="handleTbOrderDetailSelectionChange" ref="tbOrderDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品ID" prop="productId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.productId" placeholder="请输入商品ID" />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="productName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入商品名称" />
            </template>
          </el-table-column>
          <el-table-column label="商品数量" prop="number" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.number" placeholder="请输入商品数量" />
            </template>
          </el-table-column>
          <el-table-column label="商品单价" prop="unitPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.unitPrice" placeholder="请输入商品单价" />
            </template>
          </el-table-column>
          <el-table-column label="商品总金额" prop="totalPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.totalPrice" placeholder="请输入商品总金额" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/manage/order"
import { listEmp } from "@/api/manage/emp"
import { listRegion } from "@/api/manage/region"

const { proxy } = getCurrentInstance()
const { order_status } = proxy.useDict('order_status')

const orderList = ref([])
const tbOrderDetailList = ref([])
const open = ref(false)
const detailOpen = ref(false)
const dispatchOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedTbOrderDetail = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const detailTitle = ref("")
const dispatchTitle = ref("")
// 添加计算属性：根据订单区域筛选匹配的员工
const matchingEmployees = computed(() => {
  const orderRegionId = dispatchForm.value.orderId ? 
    orderList.value.find(o => o.orderId === dispatchForm.value.orderId)?.regionId : null;

  if (!orderRegionId) return employees.value;

  return employees.value.filter(emp => emp.regionId === orderRegionId);
});

// 员工列表
const employees = ref([])
// 区域列表
const regions = ref([])

const data = reactive({
  form: {},
  detailForm: {},
  dispatchForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantName: null,
    merchantPhone: null,
    status: null,
    orderNumber: null,
    empId: null,
    regionId: null
  },
  rules: {
    merchantId: [
      { required: true, message: "合作商家ID不能为空", trigger: "blur" }
    ],
    orderNumber: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],
    regionId: [
      { required: true, message: "所属区域不能为空", trigger: "change" }
    ]
  },
  dispatchRules: {
    empId: [
      { required: true, message: "请选择送货员", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules, detailForm, dispatchForm, dispatchRules } = toRefs(data)

/** 查询货单管理列表 */
function getList() {
  loading.value = true
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询员工列表 */
function getEmployees() {
  listEmp().then(response => {
    employees.value = response.rows
  })
}

/** 查询区域列表 */
function getRegions() {
  listRegion().then(response => {
    regions.value = response.rows
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 取消派单
function cancelDispatch() {
  dispatchOpen.value = false
  resetDispatch()
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    merchantId: null,
    merchantName: null,
    merchantAddress: null,
    merchantPhone: null,
    status: null,
    createTime: null,
    updateTime: null,
    orderNumber: null,
    empId: null,
    regionId: null
  }
  tbOrderDetailList.value = []
  proxy.resetForm("orderRef")
}

// 派单表单重置
function resetDispatch() {
  dispatchForm.value = {
    orderId: null,
    orderNumber: null,
    empId: null
  }
  proxy.resetForm("dispatchRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加货单管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getOrder(_orderId).then(response => {
    form.value = response.data
    tbOrderDetailList.value = response.data.tbOrderDetailList
    open.value = true
    title.value = "修改货单管理"
  })
}

/** 查看详情操作 */
function handleViewDetail(row) {
  getOrder(row.orderId).then(response => {
    detailForm.value = response.data
    detailOpen.value = true
    detailTitle.value = "订单详情 - " + response.data.orderNumber
  })
}

/** 派单操作 */
function handleDispatch(row) {
  // 获取最新的员工列表
  getEmployees()
  
  dispatchForm.value.orderId = row.orderId
  dispatchForm.value.orderNumber = row.orderNumber
  dispatchForm.value.empId = null
  dispatchOpen.value = true
  dispatchTitle.value = "派单 - " + row.orderNumber
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      form.value.tbOrderDetailList = tbOrderDetailList.value
      if (form.value.orderId != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 提交派单 */
function submitDispatch() {
  proxy.$refs["dispatchRef"].validate(valid => {
    if (valid) {
      const order = orderList.value.find(o => o.orderId === dispatchForm.value.orderId)
      if (!order) return

      const dispatchData = {
        ...order,
        empId: dispatchForm.value.empId,
        status: 2,
        tbOrderDetailList: order.tbOrderDetailList
      }

      updateOrder(dispatchData).then(response => {
        proxy.$modal.msgSuccess("派单成功");
        dispatchOpen.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError("派单失败");
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除货单管理编号为"' + _orderIds + '"的数据项？').then(function() {
    return delOrder(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 订单详情序号 */
function rowTbOrderDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 订单详情添加按钮操作 */
function handleAddTbOrderDetail() {
  let obj = {}
  obj.productId = ""
  obj.productName = ""
  obj.number = ""
  obj.unitPrice = ""
  obj.totalPrice = ""
  obj.productImage = ""
  tbOrderDetailList.value.push(obj)
}

/** 订单详情删除按钮操作 */
function handleDeleteTbOrderDetail() {
  if (checkedTbOrderDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的订单详情数据")
  } else {
    const tbOrderDetails = tbOrderDetailList.value
    const checkedTbOrderDetails = checkedTbOrderDetail.value
    tbOrderDetailList.value = tbOrderDetails.filter(function(item) {
      return checkedTbOrderDetails.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleTbOrderDetailSelectionChange(selection) {
  checkedTbOrderDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

/** 计算订单总金额 */
function calculateTotalAmount(details) {
  if (!details || details.length === 0) return 0
  return details.reduce((total, item) => {
    return total + (parseFloat(item.totalPrice) || 0)
  }, 0).toFixed(2)
}

/** 根据员工ID获取员工姓名 */
function getEmployeeName(empId) {
  if (!empId) return ''
  const employee = employees.value.find(emp => emp.employeeId === empId)
  return employee ? employee.name : empId
}

/** 根据区域ID获取区域名称 */
function getRegionName(regionId) {
  if (!regionId) return ''
  const region = regions.value.find(r => r.regionId === regionId)
  return region ? region.name : regionId
}

/** 根据订单区域ID获取匹配的员工列表 */
function getMatchingEmployees(orderRegionId) {
  if (!orderRegionId) return employees.value;
  
  // 筛选出区域ID匹配的员工
  return employees.value.filter(employee => 
    employee.regionId === orderRegionId
  );
}

// 初始化时获取员工和区域数据
onMounted(() => {
  getEmployees()
  getRegions()
  getList()
})
</script>